package com.binvshe.binvshe.app;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.Account;
import com.binvshe.binvshe.account.AccountManager;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.TokenInfo;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.contacts.ContactsService;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.model.dao.UserIconHelper;
import com.hyphenate.easeui.model.dao.UserIconMap;
import com.hyphenate.util.NetUtils;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import java.util.Timer;
import java.util.TimerTask;

import cn.hugeterry.updatefun.UpdateFunGO;
import cn.hugeterry.updatefun.config.UpdateKey;
import cn.jpush.android.api.JPushInterface;


public class MainActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback{
    private boolean mIsSetAlias = false;
    private boolean isExit=false;
    public static final int REQ_CODE_READ_CONTACT = 0X002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MainBottomFragment menuFrag = new MainBottomFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.lytMain, menuFrag).commit();
        hideToolbar();

//        initFirUpdate();

        // 检查权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {

            EasyToast.showToast(this, "权限还没有授予");
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {

            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_CONTACTS},
                        REQ_CODE_READ_CONTACT);
            }

        } else {
            ContactsService.start(this, ContactsService.ACTION_GET_CONTACTS);
        }

        //注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(mConnectionListenerclass);
//        EMAChatManager maan;
//        maan.
//        ShareHelper.share(this, MySharePlatformActivity.class, MySharePlatformActivity.makeDefaultShareData(), shareReqCode);

        configStatusBar();
    }


    SystemBarTintManager tintManager;
    private void configStatusBar() {
        RelativeLayout lytMain = (RelativeLayout) findViewById(R.id.rlytMain);
//        lytMain.setFitsSystemWindows(true);
//        lytMain.setClipToPadding(true);

        // 4.4及以上版本开启
       /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }*/

       /* tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setNavigationBarTintEnabled(true);*/


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }



        // 自定义颜色
//        tintManager.setTintColor(Color.parseColor("#003ac3ff"));
//        tintManager.setStatusBarAlpha(0);
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == REQ_CODE_READ_CONTACT) {
            if (acceptAllPermissions(permissions, grantResults)) {
                ContactsService.start(this, ContactsService.ACTION_GET_CONTACTS);
            } else {
                // Permission Denied
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK ) {
            if(!isExit) {
                isExit = true;
                Toast.makeText(this, "在按一次退出程序", Toast.LENGTH_SHORT).show();
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        isExit = false;
                    }
                }, 2000);
            } else {
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(startMain);
                System.exit(0);//退出程序
//                           finish();
            }
        }
        return false;
    }

    boolean acceptAllPermissions(String[] permissions, int[] grantResults) {
        if (grantResults != null && grantResults.length > 0) {
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }

        return true;
    }


    // 打开分享页面


    int shareReqCode = 111;

  /*  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == shareReqCode) {
            if(data != null) {
                SharePlatform platform = (SharePlatform) data.getSerializableExtra(ShareHelper.EXTRA_SHARE_PLATFORM);
                Log.e("vivi", "platform  ==  " + platform.toString()); // 分享平台
                switch (resultCode) {
                    case ShareHelper.SHARE_RESULT_CANCLE:
                        EasyToast.showToast(MainActivity.this, "分享取消");
                        break;

                    case ShareHelper.SHARE_RESULT_FAILED:
                        EasyToast.showToast(MainActivity.this, "分享失败");
                        break;

                    case ShareHelper.SHARE_RESULT_SUCCESS:
                        EasyToast.showToast(MainActivity.this, "分享成功");
                        break;
                }
            }

        }

    }*/

    private void initFirUpdate() {
        UpdateKey.API_TOKEN = "933125999ad3c5702213b10523b41e36";
        UpdateKey.APP_ID = "com.binvshe.binvshe";
//下载方式:
        UpdateKey.DialogOrNotification = UpdateKey.WITH_DIALOG;//通过Dialog来进行下载
//UpdateKey.DialogOrNotification=UpdateKey.WITH_NOTIFITION;通过通知栏来进行下载(默认)
        UpdateFunGO.init(this);
    }

    @Override
    public View createDataView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        return layoutInflater.inflate(R.layout.activity_main, null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AccountManager.getCurrentAccount() != null) {
            if (!mIsSetAlias) {
                JPushInterface.setAlias(MyApplication.getAppContext(), AccountManager.getCurrentAccount().getUserId(), null);
                Log.e("kyluzoi", ("别名" + AccountManager.getCurrentAccount().getUserId()));
                mIsSetAlias = true;
            }
        } else if (!AccountManager.isTokenValid()) {
            setRefreshToken();
        }
        UpdateFunGO.onResume(this);
        /*boolean isConnect = EMClient.getInstance().isConnected();
        Log.e("vivi", "huanxin isConnect ==   " + isConnect);
        Log.e("vivi", "current account ==   " + AccountManager.getCurrentAccount());
        if (!isConnect && AccountManager.getCurrentAccount() != null) {
            loginHuanxin(this);
        }*/
    }

    private void setRefreshToken() {
        UrlParams url = new UrlParams();
        MyHttpRequest request = new MyHttpRequest(getBaseContext());
        request.get(UrlCenter.TOKEN_REFRESH, url, new DataRequestListener<TokenInfo>(TokenInfo.class) {
            @Override
            public void onSuccess(TokenInfo tokenInfo) {
                Log.e("MainActivity", "tokenInfo :" + tokenInfo);
                // TODO
                AccountManager.updateTokenInfo(tokenInfo);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Log.e("MainActivity", "onRes=ume onFailure strMsg :" + strMsg);
            }
        });


    }


    int reconnectTimes = 0;
    //实现ConnectionListener接口
    private EMConnectionListener mConnectionListenerclass = new EMConnectionListener() {
        @Override
        public void onConnected() {
            reconnectTimes = 0;
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
                        EasyToast.showToast(MainActivity.this, "帐号已经被移除");
                    } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        EasyToast.showToast(MainActivity.this, "帐号在其他设备登录");
                    } else {
                        if (NetUtils.hasNetwork(MainActivity.this)) {
                            //连接不到聊天服务器
//                            EasyToast.showToast(MainActivity.this, "连接不到聊天服务器，正在重新连接！！");
                            // delay to reconnect
                            View view = new View(MainActivity.this);
                            //重新连接不超过3次
                            if (reconnectTimes < 3) {
                                view.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        loginHuanxin(MainActivity.this);
                                        reconnectTimes++;
                                    }
                                }, 6000);
                            }

                        } else {
                            //当前网络不可用，请检查网络设置
                            EasyToast.showToast(MainActivity.this, "当前网络不可用，请检查网络设置");
                        }

                    }
                }
            });
        }
    };

    /**
     * 登录环信
     */
    public static void loginHuanxin(final Activity context) {
        Account acct = AccountManager.getCurrentAccount();
        if (acct != null && !TextUtils.isEmpty(acct.getPhone()) && !TextUtils.isEmpty(acct.getPassWord())) {
            Log.e("vivi", "  acct getPhone  " + acct.getPhone() + "  pwd " + acct.getPassWord());
            Log.e("vivi", "  acct getUserId  " + acct.getUserId());
            EMClient.getInstance().login(acct.getPhone(), acct.getPassWord(), new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                    Account acct = AccountManager.getCurrentAccount();
                    UserIconMap map = new UserIconMap();
                    map.setAvatar(acct.getPortrait());
                    map.setUserName(acct.getPhone());
                    map.setNickName(acct.getNickName());
                    UserIconHelper.setUserIcon(context, map);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            EasyToast.showToast(context, "登录聊天服务器成功！");
                        }
                    });

                    Log.d("main", "登录聊天服务器成功！");
                }

                @Override
                public void onProgress(int progress, String status) {

                }

                @Override
                public void onError(int code, String message) {
                    Log.d("main", "登录聊天服务器失败！code = " + code);
                    Log.d("main", "登录聊天服务器失败！message = " + message);
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().removeConnectionListener(mConnectionListenerclass);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    void testGetAppAttrs() {
//        TypedArray typedArray1 = obtainStyledAttributes(R.styleable.IconTextArrowButton);
        TypedArray typedArray1 = obtainStyledAttributes(null, R.styleable.BadgeRadioButton, R.attr.badgeRadioButtonStyle, 0);
        float drawHeight = typedArray1.getDimension(R.styleable.BadgeRadioButton_drawableHeight, -1.0f);
        Log.e("vivi", "   textSize  ==  " + drawHeight);
        typedArray1.recycle();

        TypedArray typedArray = obtainStyledAttributes(R.styleable.vidroid);
        float textSize1 = typedArray.getDimension(R.styleable.vidroid_textSize1, -1.0f);
        Log.e("vivi", "   textSize1  ==  " + textSize1);
        typedArray.recycle();
    }

    @Override
    protected void onStop() {
        super.onStop();
        UpdateFunGO.onStop(this);
    }
}
